package cn.itrip.biz.controller;


import cn.itrip.beans.dtos.Dto;
import cn.itrip.beans.dtos.ErrorCode;
import cn.itrip.beans.dtos.InputDto;
import cn.itrip.beans.pojo.ItripHotel;
import cn.itrip.beans.pojo.ItripLabelDic;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.vo.ImagesVo;
import cn.itrip.beans.vo.biz.*;
import cn.itrip.biz.service.IItripCommentService;
import cn.itrip.common.Page;
import cn.itrip.common.ValidationToken;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 评论表 前端控制器
 * </p>
 *
 * @author 滕召伟
 * @since 2020-02-27
 */

@Api(tags = "酒店点评")
@RestController
@RequestMapping("/biz/api/comment")
public class ItripCommentController {
    @Resource
    IItripCommentService itripCommentService;
    @Resource
    private IItripCommentService service;
    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 获取酒店等级
     *
     * @param hotelId
     * @return
     */
    @ApiOperation(value = "酒店信息", httpMethod = "Get", protocols = "HTTP", produces = "application/json;charset=utf-8", response = InputDto.class, notes = "酒店等级")
    @GetMapping(value = "/gethoteldesc/{hotelId}", produces = "application/json;charset=utf-8")
    public Dto getInformation(@ApiParam(name = "hotelId", value = "酒店ID", required = true) @PathVariable Long hotelId) {
        ItripHotel hotel = service.getHotelId(hotelId);
        if (hotel != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("hotelName", hotel.getHotelName());
            map.put("hotelLevel", hotel.getHotelLevel());
            return InputDto.data(map);
        }
        return InputDto.error(ErrorCode.CONTENT_IS_EMPTY);
    }

    /**
     * 出游类型
     *
     * @return
     */
    @ApiOperation(value = "旅游类型", httpMethod = "Get", protocols = "HTTP", produces = "application/json;charset=utf-8", response = InputDto.class, notes = "旅游类型")
    @GetMapping(value = "/gettraveltype", produces = "application/json;charset=utf-8")
    public Dto listType() {
        List<ItripLabelDic> list = service.listParentId();
        if (list != null) {
            return InputDto.data(list);
        }
        return InputDto.error(ErrorCode.CONTENT_ACQUISITION_ERROR);
    }

    /**
     * 酒店点评
     *
     * @param comment
     */
    @ApiOperation(value = "酒店点评", httpMethod = "Post", protocols = "HTTP", produces = "application/json;charset=utf-8", response = InputDto.class, notes = "酒店点评")
    @PostMapping(value = "/add", produces = "application/json;charset=utf-8")
    public Dto saveComment(@ApiParam(name = "comment", value = "评论对象", required = true) @RequestBody ImagesVo comment,
                           HttpServletRequest request) {
        String token = request.getHeader("token");
        if ("".equals(token)) {
            return InputDto.error(ErrorCode.CONTENT_ACQUISITION_ERROR);
        }
        ValidationToken validationToken = new ValidationToken();
        ItripUser user = validationToken.getToken(token, redisTemplate);
        comment.setCreatedBy(user.getId());
        service.addComment(comment);
        return InputDto.mes("评论成功!");
    }

    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    @ApiOperation(value = "上传图片", httpMethod = "Post", protocols = "HTTP", produces = "application/json;charset=utf-8", response = InputDto.class, notes = "上传图片")
    @PostMapping(value = "/upload", produces = "application/json;charset=utf-8")
    public Dto getOriginalFilename(@ApiParam(name = "file", value = "图片路径", required = true) @RequestParam("file") MultipartFile file) {
        String name = file.getOriginalFilename();
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if ("jpg".equals(suffix)) {
            if (name != null && !"".equals(name)) {
                List<String> list = new ArrayList<>();
                String filePath = "D:/upFiles/Images/image";
                if (file.isEmpty()) {
                    return InputDto.mes("文件为空");
                }
                try {
                    uploadFile(file.getBytes(), filePath, name);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                list.add(name);
                return InputDto.data(list);
            }
        }
        return InputDto.error("图片上传失败!");
    }

    /**
     * 删除图片
     *
     * @param imgName
     * @return
     */
    @ApiOperation(value = "删除图片", httpMethod = "Post", protocols = "HTTP", produces = "application/json;charset=utf-8", response = InputDto.class, notes = "删除上传的图片")
    @PostMapping(value = "/delpic", produces = "application/json;charset=utf-8")
    public Dto deleteDelpic(@ApiParam(name = "imgName", value = "图片名称", required = true) @RequestParam Object imgName) {
        if (imgName != null & !"".equals(imgName)) {
            String imgAge = "D:/upFiles/Images/image/" + imgName;
            File file = new File(imgAge);
            file.delete();
            return InputDto.mes("图片已删除!");
        }
        return InputDto.mes("图片删除失败!");
    }


    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + "/" + fileName);
        out.write(file);
        out.flush();
        out.close();
    }

    /**
     * 根据酒店编号获取酒店综合评分
     *
     * @param hotelId
     * @return
     */
    @GetMapping("/gethotelscore/{hotelId}")
    public Dto getHotelScore(@PathVariable("hotelId") Integer hotelId) {
        if (hotelId == null) {
            return InputDto.error(ErrorCode.BIZ_PASS_VALUE_NULL);
        } else {
            GetHotelScore score = itripCommentService.GetHotelScore(hotelId);
            return InputDto.data(score);
        }
    }

    /**
     * 根据酒店编号获取评价中各类型的数量
     *
     * @param hotelId
     * @return
     */
    @GetMapping("/getcount/{hotelId}")
    public Dto getCount(@PathVariable("hotelId") Integer hotelId) {
        if (hotelId == null) {
            return InputDto.error(ErrorCode.BIZ_PASS_VALUE_NULL);
        } else {
            GetCount count = itripCommentService.GetCount(hotelId);
            return InputDto.data(count);
        }
    }

    /**
     * 根据酒店编号及类型查询评论信息
     *
     * @param list
     * @return
     */
    @PostMapping(value = "/getcommentlist",produces = "application/json;charset=utf-8")
    public Dto getCommentList(@RequestBody GetCommentList list) {
        if (list.getHotelId() == null) {
            return InputDto.error(ErrorCode.BIZ_PASS_VALUE_NULL);
        } else {
            Page<GetCommentListVo> vo = itripCommentService.GetCommentList(list);
            return InputDto.data(vo);
        }
    }

    /**
     * 根据编号获取图片路径
     *
     * @param id
     * @return
     */
    @GetMapping("/getimg/{id}")
    public Dto getImg(@PathVariable("id") Integer id) {
        if (id == null) {
            return InputDto.error(ErrorCode.BIZ_PASS_VALUE_NULL);
        } else {
            List<GetImg> list = itripCommentService.GetImg(id);
            return InputDto.data(list);
        }
    }
}